package com.wwt.mr;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class InverseStepTwo {
    public static class StepTwoMapper extends Mapper<LongWritable, Text,Text,Text> {
        //拿到的数据是k:偏移量，v:hello-->a.txt   3
        @Override
        protected void map(LongWritable key, Text value, Context context)throws IOException, InterruptedException {
            String line=value.toString();
            String[] fields= StringUtils.split(line,"\t");
            //单词和文件名
            String[] wordAndFileName=StringUtils.split(fields[0],"-->");
            //再分割出单词
            String word=wordAndFileName[0];
            //文件名
            String fileName=wordAndFileName[1];
            //出现的次数
            long count = Long.parseLong(fields[1]);
            //输出{hello a.txt-->3}
            context.write(new Text(word), new Text(fileName+"-->"+count));
        }
    }


    public static class StepTwoReducer extends Reducer<Text, Text, Text, Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            //拿到的数据<hello,{a.txt-->3,b.txt-->2,c.txt-->1}>
            String result="";
            for(Text value:values){
                result+=value+" ";
            }
            //输出的结果是key:hello v: a.txt-->3 b.txt-->2 c.txt-->1
            context.write(key, new Text(result));

        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(InverseStepTwo.class);

        job.setMapperClass(StepTwoMapper.class);
        job.setReducerClass(StepTwoReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));//手动指定输入路径
        Path path2 = new Path(args[1]);
        FileSystem fs = path2.getFileSystem(conf);
        if(fs.exists(path2))
        {
            fs.delete(path2, true);//如果存在就删除之前的输出文件路径
        }
        FileOutputFormat.setOutputPath(job,path2);//手动指定输出路径
        System.exit(job.waitForCompletion(true)?0:1);
    }
}
